package initialize

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
	"log"
	"lz/global"
)

func InitMongoDBConnect() *mongo.Database {

	var err error
	var url string
	mongoose := global.ServerConfig.Mongo
	if mongoose.Username != "" {
		///?authSource=main
		url = fmt.Sprintf("mongodb://%s:%s@%s:%v", mongoose.Username, mongoose.Password, mongoose.Url, mongoose.Port)
	} else {
		url = fmt.Sprintf("mongodb://%s:%v", mongoose.Url, mongoose.Port)
	}
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(url))
	if err != nil {
		zap.S().Fatal("[MONGO] [Fatal] %#v\n", zap.Error(err))
	}
	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		zap.S().Fatal("[MONGO] [Fatal] %#v\n", zap.Error(err))
	}
	db := client.Database(mongoose.Database)

	zap.S().Infof("mongodb 链接信息:%v", db)
	return db

}

func GetDB() *mongo.Database {
	return global.MongoDb
}

func GetCollection(name string) *mongo.Collection {
	return global.MongoDb.Collection(name)
}
func AutoRegister() {

	//Register(models.RegisterUserAction())
	//Register(models.RegisterTheaterRecord())
	//Register(models.RegisterAd() )
	//Register(models.RegisterDashStart() )
}

// 注册集合和索引
func Register(collectionName string, indexList []mongo.IndexModel) {
	db := GetDB()
	db.CreateCollection(context.TODO(), collectionName)

	collection := GetCollection(collectionName)
	indexes, err := collection.Indexes().CreateMany(context.TODO(), indexList)
	if err != nil {
		log.Fatalf("[Mongo] [Fatal] '%s' Index Create Fail: %#v", collectionName, err)
	}
	log.Printf("[Mongo] [Info] '%s' Index Create Success: %v", collectionName, indexes)
}
